<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Soaic" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="资料相关官方API： https://mp.weixin.qq.com/debug/wxadoc/dev/index.html IDE下载： https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html CSS相关 水平布局  &amp;#123;display: flex; flex-direction: row;&amp;#125;  垂直布">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序开发技巧">
<meta property="og:url" content="http://soaic.github.io/2017/08/11/小程序开发技巧/index.html">
<meta property="og:site_name" content="Soaic&#39;s Blog">
<meta property="og:description" content="资料相关官方API： https://mp.weixin.qq.com/debug/wxadoc/dev/index.html IDE下载： https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html CSS相关 水平布局  &amp;#123;display: flex; flex-direction: row;&amp;#125;  垂直布">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-17T18:02:22.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="小程序开发技巧">
<meta name="twitter:description" content="资料相关官方API： https://mp.weixin.qq.com/debug/wxadoc/dev/index.html IDE下载： https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html CSS相关 水平布局  &amp;#123;display: flex; flex-direction: row;&amp;#125;  垂直布">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://soaic.github.io/2017/08/11/小程序开发技巧/"/>





  <title>小程序开发技巧 | Soaic's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Soaic's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Soaic</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://soaic.github.io/2017/08/11/小程序开发技巧/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Soaic">
      <meta itemprop="description" content="Welcome!">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Soaic's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">小程序开发技巧</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-11T20:33:15+08:00">
                2017-08-11
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2017/08/11/小程序开发技巧/" class="leancloud_visitors" data-flag-title="小程序开发技巧">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="资料相关"><a href="#资料相关" class="headerlink" title="资料相关"></a>资料相关</h3><p>官方API： <a href="https://mp.weixin.qq.com/debug/wxadoc/dev/index.html" target="_blank" rel="external">https://mp.weixin.qq.com/debug/wxadoc/dev/index.html</a></p>
<p>IDE下载： <a href="https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html" target="_blank" rel="external">https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html</a></p>
<h3 id="CSS相关"><a href="#CSS相关" class="headerlink" title="CSS相关"></a>CSS相关</h3><blockquote>
<p>水平布局</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attribute">display</span>: flex; </div><div class="line"><span class="attribute">flex-direction</span>: row;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>垂直布局</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attribute">display</span>: flex;</div><div class="line"><span class="attribute">flex-direction</span>: column;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<a id="more"></a>
<blockquote>
<p>左右居中</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attribute">display</span>: flex;</div><div class="line"><span class="attribute">flex-direction</span>: row;</div><div class="line"><span class="attribute">align-items</span>: center;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>上下居中</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attribute">display</span>: flex;</div><div class="line"><span class="attribute">flex-direction</span>: column;</div><div class="line"><span class="attribute">align-items</span>: center;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>水平布局上下左右居中</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attribute">display</span>: flex;</div><div class="line"><span class="attribute">flex-direction</span>: row;</div><div class="line"><span class="attribute">align-items</span>: center;</div><div class="line"><span class="attribute">justify-content</span>: center;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>垂直布局上下左右居中</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attribute">display</span>: flex;</div><div class="line"><span class="attribute">flex-direction</span>: column;</div><div class="line"><span class="attribute">align-items</span>: center;</div><div class="line"><span class="attribute">justify-content</span>: center;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>按钮角度设为0</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line"><span class="selector-tag">button</span><span class="selector-pseudo">::after</span>&#123;</div><div class="line">	<span class="attribute">border-radius</span>: <span class="number">0px</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>设置全局字体样式和抗锯齿</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line"><span class="selector-tag">page</span>&#123;</div><div class="line">    <span class="attribute">font</span>: <span class="number">14px</span>/<span class="number">1.5</span> <span class="string">"Microsoft YaHei"</span>,<span class="string">"Microsoft YaHei UI"</span>, sans-serif; </div><div class="line">    <span class="attribute">-webkit-font-smoothing</span>: antialiased;</div><div class="line">    <span class="attribute">-moz-osx-font-smoothing</span>: grayscale;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>小屏幕分辨率适配</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">@<span class="keyword">media</span> only screen and (max-width:<span class="number">320px</span>)&#123;</div><div class="line">	<span class="selector-class">.phone_img</span>&#123;<span class="attribute">width</span>: <span class="number">45px</span>; <span class="attribute">height</span>: <span class="number">30px</span>;&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>超过长度显示省略号</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123;<span class="attribute">text-overflow</span>:ellipsis; <span class="attribute">white-space</span>:nowrap; <span class="attribute">overflow</span>:hidden;&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>数字强制换行</p>
</blockquote>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line">&#123; <span class="attribute">word-wrap</span>:break-word；&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>悬浮层叠布局</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="number">1</span>、z-index 重叠顺序属性 值为正整数值，数字越大对应对象层越浮上层</div><div class="line"><span class="number">2</span>、position:relative和position:absolute设置对象属性为可定位（可重叠）</div><div class="line"><span class="number">3</span>、left right top bottom绝对定位具体位置设置</div><div class="line"><span class="number">4</span>、父控件必须为position:relative和position:absolute</div></pre></td></tr></table></figure>
<blockquote>
<p>Html富文本解析展示</p>
</blockquote>
<p>使用wxParse第三方实现 </p>
<p>github地址： <a href="https://github.com/icindy/wxParse" target="_blank" rel="external">https://github.com/icindy/wxParse</a>    </p>
<h3 id="JS相关"><a href="#JS相关" class="headerlink" title="JS相关"></a>JS相关</h3><blockquote>
<p>解决小程序5层页面限制</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">intentPage</span>(<span class="params">pageUrl</span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> pageNum = getCurrentPages().length;</div><div class="line">    <span class="keyword">if</span> (!isOptStrNull(pageUrl))&#123;</div><div class="line">        <span class="keyword">if</span> (pageNum &gt;= <span class="number">5</span>) &#123;</div><div class="line">            wx.redirectTo(&#123;</div><div class="line">                url: pageUrl,</div><div class="line">            &#125;)</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            wx.navigateTo(&#123;</div><div class="line">                url: pageUrl,</div><div class="line">            &#125;)</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>页面间数据传递</p>
</blockquote>
<p>使用onfire.js第三方实现 类似Android中的EventBus 使用起来还是蛮方便的</p>
<p>github地址：<a href="https://github.com/hustcc/onfire.js" target="_blank" rel="external">https://github.com/hustcc/onfire.js</a></p>
<blockquote>
<p>格式化时间戳</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatTimeLong</span>(<span class="params">times</span>) </span>&#123;</div><div class="line">    <span class="keyword">if</span> (times.length == <span class="number">10</span>) &#123;</div><div class="line">        <span class="keyword">return</span> formatTime(<span class="keyword">new</span> <span class="built_in">Date</span>(times * <span class="number">1000</span>));</div><div class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (times.length == <span class="number">13</span>) &#123;</div><div class="line">        <span class="keyword">return</span> formatTime(<span class="keyword">new</span> <span class="built_in">Date</span>(times));</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatTime</span>(<span class="params">date</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> year = date.getFullYear()</div><div class="line">    <span class="keyword">var</span> month = date.getMonth() + <span class="number">1</span></div><div class="line">    <span class="keyword">var</span> day = date.getDate()</div><div class="line">    <span class="keyword">var</span> hour = date.getHours()</div><div class="line">    <span class="keyword">var</span> minute = date.getMinutes()</div><div class="line">    <span class="keyword">var</span> second = date.getSeconds()</div><div class="line">    <span class="keyword">return</span> [year, month, day].map(formatNumber).join(<span class="string">'-'</span>) + <span class="string">' '</span> + [hour, minute, second].map(formatNumber).join(<span class="string">':'</span>)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>判断一个属性是否为空</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">isEmpty</span>(<span class="params">str</span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> (str) == <span class="string">'undefined'</span> || str == <span class="literal">null</span> || str == <span class="string">''</span> || str == <span class="string">'null'</span> || str == <span class="string">'[]'</span> || str == <span class="string">'&#123;&#125;'</span>) &#123;</div><div class="line">        <span class="keyword">return</span> <span class="literal">true</span></div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>正则匹配手机号</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">matchRegPhone</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> reg = <span class="string">"/[1][345789]\\d&#123;9&#125;/"</span>;</div><div class="line">    <span class="keyword">var</span> result = reg.test(str);</div><div class="line">    reg.lastIndex = <span class="number">0</span>;</div><div class="line">    <span class="keyword">return</span> result;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>网络请求封装工具类 netUtil.js</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">RequestConfig</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">this</span>.page;</div><div class="line">    <span class="keyword">this</span>.url=<span class="string">''</span>;</div><div class="line">    <span class="keyword">this</span>.params=&#123;&#125;;</div><div class="line">    <span class="keyword">this</span>.netMethod=<span class="string">'GET'</span>;</div><div class="line">    <span class="keyword">this</span>.callback=&#123;</div><div class="line">        onPre: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;,</div><div class="line">        onEnd: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;,</div><div class="line">        onSuccess:<span class="function"><span class="keyword">function</span> (<span class="params">data</span>)</span>&#123;&#125;,</div><div class="line">        onError : <span class="function"><span class="keyword">function</span>(<span class="params">msgCanShow,code</span>)</span>&#123;&#125;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.callBack = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">this</span>.callback = event;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.setPage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">this</span>.page = event;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.setUrl = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">this</span>.url = event;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.setParams = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">this</span>.params = event;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.post = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        <span class="keyword">this</span>.netMethod = <span class="string">'POST'</span>;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.get = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        <span class="keyword">this</span>.netMethod = <span class="string">'GET'</span>;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">this</span>.send = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        request(<span class="keyword">this</span>);</div><div class="line">    &#125;;</div><div class="line">&#125;</div><div class="line"><span class="comment">/** todo </span></div><div class="line"><span class="comment"> 拷贝这段代码去用--RequestConfig里的callback</span></div><div class="line"><span class="comment"> onPre: function()&#123;&#125;,</span></div><div class="line"><span class="comment"> onEnd: function()&#123;&#125;,</span></div><div class="line"><span class="comment"> onSuccess:function (data)&#123;&#125;</span></div><div class="line"><span class="comment"> onError : function(msgCanShow,code,hiddenMsg)&#123;&#125;</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 注意,此方法调用后还要调用.send()才是发送出去.</span></div><div class="line"><span class="comment"> * @returns &#123;RequestConfig&#125;</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">getBuildRequest</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> RequestConfig();</div><div class="line">&#125;  </div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 封装网络请求通用的处理: 参数拼接和结果处理</span></div><div class="line"><span class="comment"> * @constant 使用buildRequest().send()来发送请求</span></div><div class="line"><span class="comment"> * @param requestConfig</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params">requestConfig</span>)</span>&#123;</div><div class="line">    <span class="comment">//请求前</span></div><div class="line">    <span class="keyword">if</span>(util.isFunction(requestConfig.callback.onPre) )&#123;</div><div class="line">        requestConfig.callback.onPre();</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">var</span> url = requestConfig.url;</div><div class="line">    <span class="keyword">var</span> body = requestConfig.params;</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">"request data start-----&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"</span>);</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">"url="</span> + url);</div><div class="line">    body = handlerCommonParams(body);</div><div class="line">    <span class="keyword">var</span> contentType =<span class="string">'application/json'</span>;</div><div class="line">    <span class="comment">//post请求逻辑</span></div><div class="line">    <span class="keyword">if</span> (requestConfig.netMethod ==<span class="string">'POST'</span>)&#123;</div><div class="line">        body = util.json2Form(body);</div><div class="line">        contentType = <span class="string">'application/x-www-form-urlencoded'</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="built_in">console</span>.log(body);</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">"method="</span>+requestConfig.netMethod);</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">"&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-----request data end"</span>);</div><div class="line">    wx.request(&#123;</div><div class="line">        url: url,</div><div class="line">        method:requestConfig.netMethod,</div><div class="line">        header:&#123;<span class="string">'Content-Type'</span>:contentType&#125;,</div><div class="line">        data:body,</div><div class="line">        success: <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</div><div class="line">            <span class="keyword">if</span>(util.isFunction(requestConfig.callback.onEnd))&#123;</div><div class="line">                requestConfig.callback.onEnd();<span class="comment">//请求发出后</span></div><div class="line">            &#125;</div><div class="line">            <span class="keyword">if</span> (res.statusCode = <span class="number">200</span>) &#123;</div><div class="line">                <span class="built_in">console</span>.log(<span class="string">"request success: "</span>+<span class="built_in">JSON</span>.stringify(res.data));</div><div class="line">                requestConfig.callback.onSuccess(res.data);</div><div class="line">            &#125;<span class="keyword">else</span> <span class="keyword">if</span>(res.statusCode &gt;= <span class="number">500</span>)&#123;</div><div class="line">                requestConfig.callback.onError(<span class="string">"服务器异常！"</span>,res.statusCode);</div><div class="line">            &#125;<span class="keyword">else</span> <span class="keyword">if</span>(res.statusCode &gt;= <span class="number">400</span> &amp;&amp; res.statusCode &lt; <span class="number">500</span>)&#123;</div><div class="line">                requestConfig.callback.onError(<span class="string">"没有找到内容"</span>,res.statusCode);</div><div class="line">            &#125;<span class="keyword">else</span>&#123;</div><div class="line">                requestConfig.callback.onError(<span class="string">"网络请求异常！"</span>,res.statusCode);</div><div class="line">            &#125;</div><div class="line">        &#125;,</div><div class="line">        fail:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">"request fail: "</span>+<span class="built_in">JSON</span>.stringify(res));</div><div class="line">            <span class="keyword">if</span>( util.isFunction(requestConfig.callback.onEnd) )&#123;</div><div class="line">                requestConfig.callback.onEnd();<span class="comment">//请求发出前</span></div><div class="line">            &#125;</div><div class="line">            requestConfig.callback.onError(<span class="string">"网络请求异常！"</span>,res.statusCode);</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 处理公共参数</span></div><div class="line"><span class="comment"> * unionid</span></div><div class="line"><span class="comment"> * wechatid</span></div><div class="line"><span class="comment"> * timestamp</span></div><div class="line"><span class="comment"> * entry</span></div><div class="line"><span class="comment"> * uid</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">handlerCommonParams</span>(<span class="params">body</span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> body;</div><div class="line">&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * json转表单</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">json2Form</span>(<span class="params">json</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> str = [];</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> p <span class="keyword">in</span> json) &#123;</div><div class="line">        str.push(<span class="built_in">encodeURIComponent</span>(p) + <span class="string">"="</span> + <span class="built_in">encodeURIComponent</span>(json[p]));</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> str.join(<span class="string">"&amp;"</span>);</div><div class="line">&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 是否是方法</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">isFunction</span>(<span class="params">value</span>) </span>&#123;</div><div class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> (value) == <span class="string">"function"</span>) &#123;</div><div class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="built_in">module</span>.exports = &#123;</div><div class="line">    getBuildRequest:getBuildRequest</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>DEMO:</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="keyword">const</span> netUtil = <span class="built_in">require</span>(<span class="string">"utils/netUtil.js"</span>);</div><div class="line"><span class="keyword">var</span> params = &#123;&#125;;</div><div class="line">netUtil.getBuildRequest()</div><div class="line">    .get() <span class="comment">//post()</span></div><div class="line">    .setUrl(url)</div><div class="line">    .setParams(params)</div><div class="line">    .callBack(&#123;</div><div class="line">        onPre: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">        &#125;,</div><div class="line">        onEnd: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">        &#125;,</div><div class="line">        onSuccess: <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</div><div class="line">        &#125;,</div><div class="line">        onError: <span class="function"><span class="keyword">function</span> (<span class="params">msgCanShow, code</span>) </span>&#123;</div><div class="line">        &#125;</div><div class="line">    &#125;).send();</div></pre></td></tr></table></figure>
<blockquote>
<p>小程序跳转同一个页面两次以上，同一个页面同时存在多个时，前一个页面的全局变量都会被后一个页面所覆盖</p>
</blockquote>
<p>解决办法：不要使用全局变量，可以存数据到page的data里使用this.data,而不要使用初始化的that</p>
<blockquote>
<p>权限获取失败处理</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="keyword">if</span> (wx.canIUse(<span class="string">"openSetting"</span>)) &#123;</div><div class="line">    wx.showModal(&#123;</div><div class="line">        showCancel: <span class="literal">true</span>,</div><div class="line">        title: <span class="string">'小程序需要你的允许才能正常使用'</span>,</div><div class="line">        content: <span class="string">'请点击“去设置”并勾选“用户信息”，然后确定即可正常使用'</span>,</div><div class="line">        confirmText: <span class="string">'去设置'</span>,</div><div class="line">        confirmColor: <span class="string">'#007aff'</span>,</div><div class="line">        success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</div><div class="line">            <span class="keyword">if</span> (res.confirm) &#123;</div><div class="line">                wx.openSetting(&#123;</div><div class="line">                    success: <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</div><div class="line">                        </div><div class="line">                    &#125;</div><div class="line">                &#125;)</div><div class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (res.cancel) &#123;</div><div class="line">                <span class="comment">//wx.navigateBack();</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    wx.showModal(&#123;</div><div class="line">        content: <span class="string">'您未授权获取资料，如需继续使用请删除小程序后重新使用并授权'</span>,</div><div class="line">        confirmColor: <span class="string">'#007aff'</span>,</div><div class="line">        showCancel: <span class="literal">false</span>,</div><div class="line">        success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</div><div class="line">            <span class="keyword">if</span> (res.confirm) &#123;</div><div class="line"></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/10/Hexo学习和使用/" rel="next" title="Hexo学习和使用">
                <i class="fa fa-chevron-left"></i> Hexo学习和使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/18/小程序接入LeanCloud学习笔记/" rel="prev" title="小程序接入LeanCloud学习笔记">
                小程序接入LeanCloud学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Soaic" />
          <p class="site-author-name" itemprop="name">Soaic</p>
           
              <p class="site-description motion-element" itemprop="description">Welcome!</p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#资料相关"><span class="nav-number">1.</span> <span class="nav-text">资料相关</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CSS相关"><span class="nav-number">2.</span> <span class="nav-text">CSS相关</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JS相关"><span class="nav-number">3.</span> <span class="nav-text">JS相关</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Soaic</span>
</div>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("nSNhFcJCeysT9vRXgfNvtbQF-gzGzoHsz", "aegQNi8pntiOE4R2z0e5B84D");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
